package com.junsi.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.junsi.common.core.domain.AjaxResult;
import com.junsi.common.core.text.Convert;
import com.junsi.common.enums.DbDialect;
import com.junsi.common.exception.BusinessException;
import com.junsi.system.domain.SysArea;
import com.junsi.system.domain.SysCity;
import com.junsi.system.mapper.SysAreaMapper;
import com.junsi.system.mapper.SysCityMapper;
import com.junsi.system.service.ISysCityService;
import com.junsi.system.vo.SysAreaCity;
import com.junsi.system.vo.SysCityVo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 省市区 服务层实现
 * 
 * @author junsi
 * @date 2019-05-30
 */
@Service
public class SysCityServiceImpl implements ISysCityService
{

	@Value("${pagehelper.helperDialect}")
	private String dbDialect;
    
	@Autowired
	private SysCityMapper cityMapper;
	@Autowired
	private SysAreaMapper areaMapper;

	/**
	 * 查询省市区信息
	 * @param cityCode 省市区ID
	 * @return 省市区信息
	 */
	@Override
	public SysCity selectCityById(Integer cityCode)
	{
		return cityMapper.selectCityById(cityCode);
	}

	/**
	 * 查询省市区列表
	 * @param city 省市区信息
	 * @return 省市区集合
	 */
	@Override
	public List<SysCity> selectCityList(SysCity city)
	{
		return cityMapper.selectCityList(city);
	}

	/**
	 * 查询省市区列表
	 * @return 省集合
	 */
	@Override
	public List<SysCity> selectCityByPRo()
	{
		return cityMapper.selectCityByPRo();
	}

	/**
	 * 查询省市区列表
	 * @param proCode 省份ID
	 * @return 市区集合
	 */
	@Override
	public List<SysCity> selectCityByCity(Integer proCode)
	{
		return cityMapper.selectCityByCity(proCode);
	}

	/**
	 * 新增省市区
	 * 
	 * @param city 省市区信息
	 * @return 结果
	 */
	@Override
	public int insertCity(SysCity city)
	{
		SysCity data = cityMapper.selectCityById(city.getParentCode());
		city.setParentCodes((data.getParentCodes() + "," + data.getParentCode()));
    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
    		return cityMapper.insertCity(city);
    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
    		return cityMapper.insertCityOracle(city);
    	} else {
    		return 0;
    	}
	}

	/**
	 * 修改省市区
	 * 
	 * @param city 省市区信息
	 * @return 结果
	 */
	@Override
	public int updateCity(SysCity city)
	{
		return cityMapper.updateCity(city);
	}

	/**
	 * 删除省市区对象
	 * 
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteCityByIds(String ids)
	{
		return cityMapper.deleteCityByIds(Convert.toStrArray(ids));
	}

	/**
	 * 查询城市数量
	 * @param cityCode 城市编码
	 * @return 城市数量
	 */
	@Override
	public List<SysAreaCity> selectCityNum(String areaCode, String cityCode)
	{
		return cityMapper.selectCityNum(areaCode, Convert.toStrArray(cityCode));
	}

	/**
	 * 新增保存省市区
	 * @param loginName 当前用户
	 * @param loginName 当前用户
	 * @param cityCode 城市编码
	 * @param name 区域名称
	 * @param areaName 所属大区
	 * @param status 状态
	 * @return 结果
	 */
	@Override
	public AjaxResult addSave(String status, String areaName, String areaCode
			, String parentCode, String submitParentsCodes, String loginName)
	{
		//区/县编码
		String regionCode = "";
		JSONArray array = JSONArray.fromObject(submitParentsCodes);
		for (int j= 0;j<array.size();j++){
			JSONObject json=array.getJSONObject(j);
			//level-城市级别：0-中国、1-省、2-市、3-区/县
			if ("3".equals(json.getString("level"))) {
				regionCode += json.getString("cityCode") + ",";
			}		
		}
		//查询除本区域外是否已存在城市编码
		List<SysAreaCity> num = cityMapper.selectCityNum(areaCode, Convert.toStrArray(regionCode));
		for (SysAreaCity sysAreaCity : num) {
			//判断城市是否已存在
			if (sysAreaCity.getNum() == 1 && !"1".equals(status)) {
				return AjaxResult.error(String.format(sysAreaCity.getCityName() + "已存在"));
			}
		}
		if (null != areaCode && !"".equals(areaCode)) {
			//根据区域编码，删除区域相关城市
			areaMapper.deleteByArea(areaCode);
			SysArea area = areaMapper.selectAreaById(areaCode);
			SysArea par = areaMapper.selectAreaById(parentCode);
			area.setAreaName(areaName);
			area.setAreaNames(par.getAreaName());
			area.setParentCode(Integer.valueOf(parentCode));
			area.setParentCodes(par.getParentCodes() + "," + par.getAreaCode());
			area.setStatus(status);
			area.setUpdateBy(loginName);
			area.setUpdateTime(new Date());
			areaMapper.updateArea(area);
			for (int j= 0;j<array.size();j++){
				JSONObject json=array.getJSONObject(j);
				SysAreaCity areaCity = new SysAreaCity();
				areaCity.setAreaCode(String.valueOf(area.getAreaCode()));
				areaCity.setCityCode(json.getString("cityCode"));
				areaCity.setLvl(json.getString("level"));
				areaCity.setCheckChildState(json.getString("check_Child_State"));
		    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
					areaMapper.insertAreaCity(areaCity);
		    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
					areaMapper.insertAreaCityOracle(areaCity);
		    	}
			}
		}else {
			//新增
			if (array.size() != 0) {
				areaMapper.deleteByArea(areaCode);
				//todo 将此处业务处理逻辑移至 service层   ，并添加事物回滚注解
				/**
				 * 在xml insert 方法头部设定以下参数
				 * useGeneratedKeys="true" 表示给主键设置自增长
				 * keyProperty="userId"  表示将自增长后的Id赋值给实体类中的userId字段。
				 * 
				 */
				SysArea area = new SysArea();
				SysArea par = areaMapper.selectAreaById(parentCode);
				area.setAreaName(areaName);
				area.setParentCode(par.getAreaCode());
				area.setParentCodes(par.getParentCodes() + "," + par.getAreaCode());
				area.setAreaNames(par.getAreaName());
				area.setCreateBy(loginName);
				area.setCreateTime(new Date());
				area.setUpdateBy(loginName);
				area.setUpdateTime(new Date());
				area.setLvl(2);
				area.setStatus(status);
		    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
					areaMapper.insertArea(area); //方法内部 空指针错误
		    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
					areaMapper.insertAreaOracle(area); //方法内部 空指针错误
		    	}
				for (int j= 0;j<array.size();j++){
					JSONObject json=array.getJSONObject(j);
					SysAreaCity areaCity = new SysAreaCity();
					areaCity.setAreaCode(String.valueOf(area.getAreaCode()));
					areaCity.setCityCode(json.getString("cityCode"));
					areaCity.setLvl(json.getString("level"));
					areaCity.setCheckChildState(json.getString("check_Child_State"));
			    	if(DbDialect.MYSQL.getCode().equals(dbDialect)) {
						areaMapper.insertAreaCity(areaCity);
			    	} else if(DbDialect.ORACLE.getCode().equals(dbDialect)) {
						areaMapper.insertAreaCityOracle(areaCity);
			    	}
				}
			} else {
				return AjaxResult.error(String.format("请选择城市"));
			}
		}
		return AjaxResult.success();
	}

	/**
	 * 修改保存省市区
	 * @param city 城市信息
	 * @param cityCode 城市编码
	 */
	@Override
	public int editSave(SysCity city,String cityCode)throws BusinessException
	{
		return cityMapper.updateCity(city);
	}


	/**
	 * 查询数量
	 * @param cityCode 城市编码
	 * @return 城市数量
	 */
	public List<SysCity> selectCity(Integer proCode,String areaCode){
		Map<Integer, SysCity> map =new  HashMap<Integer,SysCity>();
		List<SysCity> list = new ArrayList<SysCity>();
		List<SysCity> proList = cityMapper.selectCityByCity(proCode);
		if (!"".equals(areaCode) && null != areaCode) {
			List<SysCity> cityList = cityMapper.selectCityByArea(proCode,areaCode);
			for (SysCity sysCity : cityList) {
				list.add(sysCity);
			}
		}
		for (SysCity sysCity : proList) {
			list.add(sysCity);
		}
		for (SysCity sysCity : list) {
			map.put(sysCity.getCityCode(), sysCity);
		}
		List<SysCity> datalist = new ArrayList<SysCity>();
		Object[] key_arr = map.keySet().toArray();
		Arrays.sort(key_arr);
		for  (Object key : key_arr) {
			SysCity sysCity = map.get(key);
			datalist.add(sysCity);
		}
		return datalist;
	}


	/**
	 * 处理省市区数据
	 */
	public List<SysCityVo> cityList(String areaCode){
		//所有省市区数据
		List<SysCity> allCityList = cityMapper.selectCityList(new SysCity());
		//全选
		List<SysCityVo> checkAll = new ArrayList<SysCityVo>();
		//未全选
		List<SysCityVo> unCheckAll = new ArrayList<SysCityVo>();
		List<SysCityVo> otherUnCheckCityNum = cityMapper.selectOtherUnCheckCityNum(areaCode);
		if (null != otherUnCheckCityNum && otherUnCheckCityNum.size() > 0) {
			for (SysCityVo unCheck : otherUnCheckCityNum) {
				//查询市级子节点数量
				SysCityVo realNum = cityMapper.selectNumByPar(String.valueOf(unCheck.getParentCode()));
				if (unCheck.getNum().intValue() == realNum.getNum().intValue()) {
					//添加全选-市
					checkAll.add(realNum);
				}else {
					//添加未全选-市
					unCheckAll.add(unCheck);
				}
			}
		}
		if (null != checkAll && checkAll.size() > 0) {
			int[] ids=new int[checkAll.size()];
			for (int i = 0; i < checkAll.size(); i++) {
				ids[i] = checkAll.get(i).getParentCode();
			}
			List<SysCityVo> checkNum = cityMapper.selectCheckNum(ids);
			if (null != checkNum && checkNum.size() > 0) {
				for (SysCityVo sysCityVo : checkNum) {
					SysCityVo realNum = cityMapper.selectNumByPar(String.valueOf(sysCityVo.getParentCode()));
					if (sysCityVo.getNum().intValue() == realNum.getNum().intValue()) {
						//添加全选-省
						checkAll.add(realNum);
					}else {
						//添加未全选-省
						unCheckAll.add(sysCityVo);
					}
				}
			}
		}
		
		//其他区域已选-级别3
		List<SysCityVo> otherUseCity = cityMapper.selectOtherUseCity(areaCode);
		//本区域选择数据
		List<SysCityVo> areaUseCity = cityMapper.selectAreaUseCity(areaCode);
		List<SysCityVo> cityList = new ArrayList<SysCityVo>();
		if (null != allCityList && allCityList.size() > 0) {
			for (SysCity sysCity : allCityList) {
				SysCityVo vo = new SysCityVo();
				vo.setCityCode(sysCity.getCityCode());
				vo.setLevel(sysCity.getLvl());
				vo.setName(sysCity.getName());
				vo.setParentCode(sysCity.getParentCode());
				vo.setType(0);
				//type:0-未选、1-其他区域全选、2-本区域已选、3-其他区域未全选
				if (null != checkAll && checkAll.size() > 0) {
					for (SysCityVo sysCityVo : checkAll) {
						if (sysCity.getCityCode().intValue() == sysCityVo.getParentCode().intValue()) {
							vo.setType(1);
						}
					}
				}
				
				if (null != unCheckAll && unCheckAll.size() > 0) {
					for (SysCityVo sysCityVo : unCheckAll) {
						if (sysCity.getCityCode().intValue() == sysCityVo.getParentCode().intValue()) {
							vo.setType(3);
						}
					}
				}
				
				if (null != areaUseCity && areaUseCity.size() > 0) {
					for (SysCityVo areaVo : areaUseCity) {
						if (sysCity.getCityCode().intValue() == areaVo.getCityCode().intValue()) {
							vo.setType(2);
						}
					}
				}
				
				if (null != otherUseCity && otherUseCity.size() > 0) {
					for (SysCityVo sysCityVo : otherUseCity) {
						if (sysCity.getCityCode().intValue() == sysCityVo.getCityCode().intValue()) {
							vo.setType(1);
						}
					}
				}
				cityList.add(vo);
			}
		}
		return cityList;
	}
}
